<?php
/**
 * Created by PhpStorm.
 * User: zhangrxiang
 * Date: 2016/12/21
 * Time: 9:59
 */


//IteratorAggregate（聚合式迭代器）接口 ¶

class TestIteratorAggregate implements IteratorAggregate{

	private $data;
	function __construct(...$a) {
		$this->data = $a;
	}

	function TestIteratorAggregate(...$a){
		$this->data = $a;
	}
	/**
	 * Retrieve an external iterator
	 * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
	 * @return Traversable An instance of an object implementing <b>Iterator</b> or
	 * <b>Traversable</b>
	 * @since 5.0.0
	 */
	public function getIterator() {
		return new ArrayIterator($this->data);
	}
}

//$testIteratorAggregate = new TestIteratorAggregate( 1, 2, 3, 4, 5, 6 );
$testIteratorAggregate = new TestIteratorAggregate( "a","b","c" );
//var_dump($testIteratorAggregate->getIterator());
foreach ( $testIteratorAggregate->getIterator() as  $key =>$value) {
	echo($value.PHP_EOL);
}

class myData1 implements IteratorAggregate {
	public $property1 = "Public property one";
	public $property2 = "Public property two";
	public $property3 = "Public property three";

	public function __construct() {
		$this->property4 = "last property";
	}

	public function getIterator() {
		return new ArrayIterator($this);
	}
}

$obj = new myData1;

foreach($obj as $key => $value) {
	echo $key." : ". $value;
	echo "\n";
}


class myData implements IteratorAggregate {

	private $array = [];
	const TYPE_INDEXED = 1;
	const TYPE_ASSOCIATIVE = 2;

	public function __construct( array $data, $type = self::TYPE_INDEXED ) {
		reset($data);
		while( list($k, $v) = each($data) ) {
			$type == self::TYPE_INDEXED ?
				$this->array[] = $v :
				$this->array[$k] = $v;
		}
	}

	public function getIterator() {
		return new ArrayIterator($this->array);
	}

}

$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',] /*TYPE 1 or 2*/ );

foreach($obj as $key => $value) {
	var_dump($key, $value);
	echo PHP_EOL;
}